﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Ext.Net;
using VTV.TaskManagementSystem.Common.Constant;

namespace VTV.TaskManagementSystem.WebApp.Admin.Team
{
    public partial class List : System.Web.UI.Page
    {
        private static bool _isUpdate;
        private static int _teamID;
        private static string _teamName;
        private static int _employeeID;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (Session["UserID"] == null || Session["UserName"] == null || Session["RoleLevel"] == null)
            {
                Response.Redirect("~/Admin/Login.aspx?return=/Admin/Team/List.aspx");
            }
        }

        protected void btnAdd_Click(object sender, DirectEventArgs e)
        {
            _isUpdate = false;
            this.windowDetailTeam.Icon = Icon.GroupAdd;
            this.windowDetailTeam.Title = "Thêm mới";
            this.windowDetailTeam.Show();
        }

        protected void btnSave_Click(object sender, DirectEventArgs e)
        {
            var obj = new BusinessLogic.Team();
            var entityData = new Entities.Team
            {
                TeamID = !String.IsNullOrEmpty(this.TeamID.Text.Trim()) ? Convert.ToInt32(this.TeamID.Text) : 0,
                Name = String.IsNullOrEmpty(txtName.Text.Trim()) ? string.Empty : txtName.Text.Trim(),
                Note = String.IsNullOrEmpty(txtNote.Text.Trim()) ? string.Empty : txtNote.Text.Trim()
            };

            if (_isUpdate)
            {
                var result = obj.Update(entityData);

                if (result)
                {
                    this.storeEmployee.Reload();

                    X.Msg.Notify(SystemInfoMessage.SYS_TITLE_VN, AuditInfoMessage.UPDATE_SUCCESS_DETAIL_VN.Replace("{0}", txtName.Text)).Show();
                }
                else
                {
                    X.Msg.Notify(SystemInfoMessage.SYS_TITLE_VN, AuditInfoMessage.AUDIT_FAILSE_VN.Replace("{0}", obj.ErrorMessage)).Show();
                }
            }
            else
            {
                var result = obj.AddNew(entityData);

                if (result)
                {
                    this.storeEmployee.Reload();

                    X.Msg.Notify(SystemInfoMessage.SYS_TITLE_VN, AuditInfoMessage.INSERT_SUCCESS_DETAIL_VN.Replace("{0}", txtName.Text)).Show();
                }
                else
                {
                    X.Msg.Notify(SystemInfoMessage.SYS_TITLE_VN, AuditInfoMessage.AUDIT_FAILSE_VN.Replace("{0}", obj.ErrorMessage)).Show();
                }
            }
        }

        protected void gridTeam_OnCommand(object sender, DirectEventArgs e)
        {
            _teamID = Convert.ToInt32(e.ExtraParams["TeamID"]);
            var command = e.ExtraParams["Command"];

            if (command.Equals("Edit"))
            {
                _isUpdate = true;
                var obj = new BusinessLogic.Team();
                var entity = obj.GetTeam(_teamID);

                if (entity != null && string.IsNullOrEmpty(obj.ErrorMessage))
                {
                    if (!this.SetValue(entity))
                    {
                        this.btnSave.Enable(false);
                        X.Msg.Notify(AuditInfoMessage.AUDIT_TITLE_VN, AuditInfoMessage.TRANSFER_FAILSE_VN + "<BR>" + AuditHelpMessage.PLS_BACK_LASTER).Show();
                    }
                }

                this.windowDetailTeam.Icon = Icon.GroupEdit;
                this.windowDetailTeam.Title = "Cập nhật thông tin";
                this.windowDetailTeam.Show();
            }
            else
            {
                X.Msg.Confirm(AuditInfoMessage.AUDIT_TITLE_VN, AuditInfoMessage.DELETE_CONFIRM_VN,
                              new MessageBoxButtonsConfig()
                              {
                                  Yes = new MessageBoxButtonConfig
                                  {
                                      Text = "Xác nhận",
                                      Handler = "Team.List.DeleteTeam()"
                                  },
                                  No = new MessageBoxButtonConfig
                                  {
                                      Text = "Quay lại"
                                  }

                              }).Show();
            }

        }

        protected void storeEmployee_OnReadData(object sender, StoreReadDataEventArgs e)
        {
            var start = e.Start;
            var limit = e.Limit;

            var source = new BusinessLogic.Team().GetAll(start, limit);
            var total = new BusinessLogic.Team().GetCount();

            if (source != null && source.Any() && total != null)
            {
                var data = new Paging<Entities.Team>(source, (int)total);

                e.Total = data.TotalRecords;

                this.storeEmployee.DataSource = data.Data;
                this.storeEmployee.DataBind();
            }
        }

        [DirectMethod(Namespace = "Team.List", ShowMask = true)]
        public void DeleteTeam()
        {
            var obj = new BusinessLogic.Team();
            var entity = obj.GetTeam(_teamID);
            if (entity != null && string.IsNullOrEmpty(obj.ErrorMessage))
            {
                var result = obj.Delete(entity);

                if (result)
                {
                    this.storeEmployee.Reload();

                    X.Msg.Notify(SystemInfoMessage.SYS_TITLE_VN, AuditInfoMessage.DELETE_SUCCESS_VN).Show();
                }
                else
                {
                    X.Msg.Notify(SystemInfoMessage.SYS_TITLE_VN, AuditInfoMessage.AUDIT_FAILSE_VN.Replace("{0}", obj.ErrorMessage)).Show();
                }
            }
            //X.Msg.Notify("delete", _teamID.ToString()).Show();
        }

        [DirectMethod(Namespace = "Team.List", ShowMask = true)]
        public void DeleteEmployee()
        {
            var obj = new BusinessLogic.EmployeeTeam();
            var entity = obj.GetEmployeeTeam(_employeeID, _teamID);
            if (entity != null && string.IsNullOrEmpty(obj.ErrorMessage))
            {
                var result = obj.Delete(entity);

                if (result)
                {
                    var source = new BusinessLogic.EmployeeTeam().GetByTeam(_teamID);
                    this.store1.DataSource = source;
                    this.store1.DataBind();

                    X.Msg.Notify(SystemInfoMessage.SYS_TITLE_VN, AuditInfoMessage.DELETE_SUCCESS_VN).Show();
                }
                else
                {
                    X.Msg.Notify(SystemInfoMessage.SYS_TITLE_VN, AuditInfoMessage.AUDIT_FAILSE_VN.Replace("{0}", obj.ErrorMessage)).Show();
                }
            }
        }

        private bool SetValue(Entities.Team entity)
        {
            try
            {
                txtName.Text = entity.Name;
                txtNote.Text = entity.Note;
                TeamID.Text = entity.TeamID.ToString();

                return true;
            }
            catch (Exception e)
            {
                return false;
            }
        }

        private bool SetValue(Entities.EmployeeTeam entity)
        {
            try
            {
                var employeeName = new BusinessLogic.Employee().GetEmployee(Convert.ToInt32(hiddenEmployeeID.Text)).FullName;
                cbbEmployeeList.Text = employeeName;

                ckbIsTeamLead.Checked = entity.IsTeamLead ?? false;

                return true;
            }
            catch (Exception e)
            {
                return false;
            }
        }

        protected void gridTeam_OnRowSelected(object sender, DirectEventArgs e)
        {
            _teamID = Convert.ToInt32(e.ExtraParams["TeamID"]);
            var teamName = e.ExtraParams["TeamName"];
            _teamName = teamName;

            this.hiddenTeamID.Text = _teamID.ToString();
            this.pnlEmployeeList.Title = teamName + " - Danh sách thành viên";

            var source = new BusinessLogic.EmployeeTeam().GetByTeam(Convert.ToInt32(e.ExtraParams["TeamID"]));
            if (source != null)
            {
                this.store1.DataSource = source;
                this.store1.DataBind();
            }
        }

        protected void btnAddEmployee_Click(object sender, DirectEventArgs e)
        {
            if (!String.IsNullOrEmpty(hiddenTeamID.Text))
            {
                _isUpdate = false;
                cbbEmployeeList.ReadOnly = false;
                this.windowDetailEmployee.Icon = Icon.Add;
                this.windowDetailEmployee.Title = _teamName + " - Thêm nhân viên";
                this.windowDetailEmployee.Show();
            }
        }

        protected void gridEmployee_OnCommand(object sender, DirectEventArgs e)
        {
            var employeeID = e.ExtraParams["EmployeeID"];
            _employeeID = Convert.ToInt32(employeeID);
            var teamID = e.ExtraParams["TeamID"];
            _teamID = Convert.ToInt32(teamID);
            var command = e.ExtraParams["Command"];

            this.hiddenEmployeeID.Text = employeeID;
            this.hiddenTeamID.Text = teamID;

            if (command.Equals("Edit"))
            {
                _isUpdate = true;
                var obj = new BusinessLogic.EmployeeTeam();
                var entity = obj.GetEmployeeTeam(Convert.ToInt32(employeeID), Convert.ToInt32(teamID));

                if (entity != null && string.IsNullOrEmpty(obj.ErrorMessage))
                {
                    if (!this.SetValue(entity))
                    {
                        this.btnSave.Enable(false);
                        X.Msg.Notify(AuditInfoMessage.AUDIT_TITLE_VN, AuditInfoMessage.TRANSFER_FAILSE_VN + "<BR>" + AuditHelpMessage.PLS_BACK_LASTER).Show();
                    }
                }

                this.cbbEmployeeList.ReadOnly = true;
                this.windowDetailEmployee.Icon = Icon.ReportEdit;
                this.windowDetailEmployee.Title = "Cập nhật thông tin";
                this.windowDetailEmployee.Show();
            }
            else
            {
                X.Msg.Confirm(AuditInfoMessage.AUDIT_TITLE_VN, AuditInfoMessage.DELETE_CONFIRM_VN,
                              new MessageBoxButtonsConfig()
                              {
                                  Yes = new MessageBoxButtonConfig
                                  {
                                      Text = "Xác nhận",
                                      Handler = "Team.List.DeleteEmployee()"
                                  },
                                  No = new MessageBoxButtonConfig
                                  {
                                      Text = "Quay lại"
                                  }

                              }).Show();
            }
        }

        protected void storestoreEmployeeCBB_OnReadData(object sender, StoreReadDataEventArgs e)
        {
            var store = sender as Store;
            var filter = e.Parameters["query"];
            var start = e.Start;
            var limit = e.Limit;

            int total;

            var source = new BusinessLogic.Employee().FilterByName(start, limit, filter, out total);

            if (source != null && source.Any() && total != -1)
            {
                var pagingData = new Paging<Entities.Employee>(source, total);

                e.Total = pagingData.TotalRecords;

                store.DataSource = pagingData.Data;
                store.DataBind();
            }
        }

        protected void btnSaveEmployee_Click(object sender, DirectEventArgs e)
        {
            var obj = new BusinessLogic.EmployeeTeam();
            //var tid = cbbTeamList.SelectedItem.Value;
            var entityData = new Entities.EmployeeTeam()
            {
                EmployeeID = !String.IsNullOrEmpty(this.hiddenEmployeeID.Text.Trim()) ? Convert.ToInt32(this.hiddenEmployeeID.Text) : -1,
                IsTeamLead = ckbIsTeamLead.Checked,
                TeamID = !String.IsNullOrEmpty(this.hiddenTeamID.Text.Trim()) ? Convert.ToInt32(this.hiddenTeamID.Text) : -1,
                Note = !String.IsNullOrEmpty(this.txtEmployeeNote.Text.Trim()) ? this.txtEmployeeNote.Text : string.Empty,
            };

            if (_isUpdate)
            {
                var result = obj.Update(entityData);

                if (result)
                {
                    var source = new BusinessLogic.EmployeeTeam().GetByTeam(Convert.ToInt32(hiddenTeamID.Text));
                    this.store1.DataSource = source;
                    this.store1.DataBind();

                    X.Msg.Notify(SystemInfoMessage.SYS_TITLE_VN, AuditInfoMessage.UPDATE_SUCCESS_VN).Show();
                }
                else
                {
                    X.Msg.Notify(SystemInfoMessage.SYS_TITLE_VN, AuditInfoMessage.AUDIT_FAILSE_VN.Replace("{0}", obj.ErrorMessage)).Show();
                }
            }
            else
            {
                entityData.EmployeeID = Convert.ToInt32(cbbEmployeeList.SelectedItem.Value);
                var result = obj.AddNew(entityData);

                if (result)
                {
                    var source = new BusinessLogic.EmployeeTeam().GetByTeam(Convert.ToInt32(hiddenTeamID.Text));
                    this.store1.DataSource = source;
                    this.store1.DataBind();

                    X.Msg.Notify(SystemInfoMessage.SYS_TITLE_VN, AuditInfoMessage.INSERT_SUCCESS_VN).Show();
                }
                else
                {
                    X.Msg.Notify(SystemInfoMessage.SYS_TITLE_VN, AuditInfoMessage.AUDIT_FAILSE_VN.Replace("{0}", obj.ErrorMessage)).Show();
                }
            }
        }
    }
}